package com.project.servlet;

import com.project.bean.UserBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.Enumeration;

public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //将表单数据封装为用户对象
        UserBean user = new UserBean();
        this.fullBean(user,req);
        resp.getWriter().print(user.toString());
    }

    private void fullBean(Object beanObj,HttpServletRequest req){
        //得到表单数据的键名称
        Enumeration<String> en = req.getParameterNames();
        try {
            while (en.hasMoreElements()) {//判断是否有下一个元素
                //取出下一个元素
                String str = en.nextElement();
                //根据表单名，得到表单值
                String value = req.getParameter(str);
                //根据属性名（和表单名一致），得到属性值
                Field f = beanObj.getClass().getDeclaredField(str);
                f.setAccessible(true);
                //根据不同的属性类型，完成类型转换
                if(f.getType() == String.class){
                    f.set(beanObj,value);
                }
                else if(f.getType() == int.class || f.getType() == Integer.class){
                    f.set(beanObj,Integer.parseInt(value));
                }
                else if(f.getType() == double.class || f.getType() == Double.class){
                    f.set(beanObj,Double.parseDouble(value));
                }
                else if(f.getType() == LocalDate.class){
                    f.set(beanObj,LocalDate.parse(value));
                }
                else if(f.getType() == String[].class){
                    f.set(beanObj,req.getParameterValues(str));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
